package net.chrisrichardson.ec2deployer.core

import groovy.mock.interceptor.MockFor
import org.jets3t.apps.synchronize.Synchronize

class S3SynchronizerTest extends GroovyTestCase {

    AWSProperties awsProperties
    MockFor mockSynchronize
    S3Synchronizer s3Synchronizer
    MockFor mockEC2Server
    
    void setUp() {
        super.setUp()
        def properties = new Properties()
        properties.setProperty("accessKey", "myAccessKey")
        properties.setProperty("secretKey", "mySecretKey")
        awsProperties = new AWSProperties(properties)
        mockSynchronize = new MockFor(Synchronize)
        s3Synchronizer = new S3Synchronizer(awsProperties)
        mockEC2Server = new MockFor(EC2Server)

    }

    void testUploadToS3() {
        mockSynchronize.demand.run { bucket, files, direction, something, acl ->
            assertEquals "myAccessKey.myPrefix-myBucket", bucket
            assertEquals "UP", direction
            assertEquals "PRIVATE", acl

        }
        mockSynchronize.use {
            s3Synchronizer.uploadToS3( ["myDir"], "myPrefix", "myBucket")
        }

    }

    void testDowloadFromS3() {
        mockEC2Server.demand.ssh {command, input ->
            assertEquals "rm -f /mnt/synchronize.properties ; cat > /mnt/synchronize.properties; chmod 0600 /mnt/synchronize.properties", command
            assertEquals """
accesskey=${awsProperties.accessKey}
secretkey=${awsProperties.secretKey}
""", input
        }

        mockEC2Server.demand.ssh { command ->
            assertEquals "/var/lib/jets3t-0.5.0/bin/synchronize.sh -q DOWN myAccessKey.myPrefix-myBucket /myDir", command
        }
        
        mockEC2Server.use {
        mockSynchronize.use {
            def host = new EC2Server()
            s3Synchronizer.downloadFromS3(host, "myPrefix", "myBucket", "/myDir")
        }
        }

    }
    
    void testMakePrefixedBucket_null() {
        assertEquals "mybucket", s3Synchronizer.makePrefixedBucket(null, "mybucket")
    }

    void testMakePrefixedBucket_empty() {
        assertEquals "mybucket", s3Synchronizer.makePrefixedBucket("", "mybucket")
    }

    void testMakePrefixedBucket_specified() {
        assertEquals "myPrefix-mybucket", s3Synchronizer.makePrefixedBucket("myPrefix", "mybucket")
    }

}